<?php

namespace App\Http\Controllers\Personal;
use App\Models\Personal\Interview;
use App\Models\Personal\PersonalLoginRecord;
use App\Models\Personal\Resume;
use Illuminate\Http\Request;
use App\Models\Personal\PersonalUser;
use App\Http\Requests\Personal\Login\AjaxLoginRequest;
use App\Models\Company\CompanyJob;
use League\Flysystem\Exception;
use Style,Site,Auth,Session;
require_once(app_path('Vendor/MpWeiXin/MpWeiXin.php'));
class MpWeiXinController extends CommonController{
    private $access_token='';//access_token 默认值为空

    /**
     * 微信链接页面
     * @param Request $request
     */
    public function WeiXinLink(Request $request)
    {
        $echoStr = $request->input('echostr');
        if (isset($echoStr)) {
            $wechatObj = new \MpWeiXin();
            $wechatObj->valid('personal');//$request
            exit;
        }

        $postStr = file_get_contents('php://input');

        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch($RX_TYPE)
            {
                case "text":
                    $resultStr = $this->handleText($postObj);
                    break;
                case "event":
                    $resultStr = $this->handleEvent($postObj);
                    break;
                default:
                    $resultStr = "Unknow msg type: ".$RX_TYPE;
                    break;
            }
            return response($resultStr)->header('Content-Type', "text/xml");
        }else {
            echo "";
            exit;
        }
    }

    /**
     * 个人用户搜索 图文回复
     * @param $postObj
     * @return string
     */
    public function handleText($postObj)
    {
        $toUsername = $postObj->ToUserName;
        $fromUsername = $postObj->FromUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $firstPigUrl = asset("default/images/mobile/layout/weichatsearchbg.png");//第一副大图 背景图
        $firstLink = url("mobile/job");  //第一副大图 链接
        $pigurl = asset("default/images/mobile/layout/jiantou.png"); //列表 右边背景图

        $CompanyJob = CompanyJob::select('id','job_title')->where('job_title','like','%'.$keyword.'%')->take(6)->get();

        if(count($CompanyJob) > 0){
            $title = "共搜索到{".count($CompanyJob)."}".$keyword."关联岗位";
            $countnews = count($CompanyJob) + 1;
            $msgType = "news";
            $textTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <ArticleCount>$countnews</ArticleCount>
                <Articles>

                <item>
                <Title><![CDATA[".$title."]]></Title>
                <Description><![CDATA[描述]]></Description>
                <PicUrl><![CDATA[$firstPigUrl]]></PicUrl>
                <Url><![CDATA[$firstLink]]></Url>
                </item>
            ";
            foreach($CompanyJob as $v){
                $url = url("jobinfo_".idEncryption($v->id).".html");
                $textTpl .="<item>
                    <Title><![CDATA[".$v->job_title."]]></Title>
                    <Description><![CDATA[".$v->job_title."]]></Description>
                    <PicUrl><![CDATA[$pigurl]]></PicUrl>
                    <Url><![CDATA[$url]]></Url>
                    </item>";
            }

            $textTpl .= "</Articles></xml>";

            $resultStr = sprintf($textTpl,$fromUsername,$toUsername , $time, $msgType);
        }else{
            $msgType = "text";
            $contentStr = "抱歉，未找到相关信息";
            $textTpl="<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					</xml>
					";
            $resultStr = sprintf($textTpl,$fromUsername,$toUsername , $time, $msgType, $contentStr);
        }

        return $resultStr;
    }

    /**
     * 消息 中心
     * @param $object
     */
    public function messageCenter($postObj, $extLink){
        $toUsername = $postObj->ToUserName;
        $fromUsername = $postObj->FromUserName;

        $time = time();
        $firstPigUrl = asset("default/images/mobile/layout/havenewmessage.png");//第一副大图 背景图
        $firstLink = url("mobile/personal/welcome")."/?wechatmpopenid=$fromUsername&$extLink";//第一副大图 链接
        $pigurl = asset("default/images/mobile/layout/jiantou.png"); //列表 右边背景图

        $msgType = "news";
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <ArticleCount>3</ArticleCount>
            <Articles>

            <item>
            <Title><![CDATA[消息中心]]></Title>
            <Description><![CDATA[描述]]></Description>
            <PicUrl><![CDATA[$firstPigUrl]]></PicUrl>
            <Url><![CDATA[$firstLink]]></Url>
            </item>
        ";
            //面试
            $Link = url("mobile/personal/interview")."/?wechatmpopenid=$fromUsername&$extLink";
            //获得用户uid
            $user = PersonalUser::select('uid')->where('wechatmpopenid',$fromUsername)->first();
            $InterviewCount = Interview::where('personal_uid',$user->uid)->where('status',0)->count();
            $textTpl .="<item>
                <Title><![CDATA[邀请我面试($InterviewCount)]]></Title>
                <Description><![CDATA[]]></Description>
                <PicUrl><![CDATA[$pigurl]]></PicUrl>
                <Url><![CDATA[$Link]]></Url>
                </item>";

            //我的简历
            $Link = url("mobile/personal/my_resume")."/?wechatmpopenid=$fromUsername&$extLink";
            $textTpl .="<item>
                <Title><![CDATA[我的简历]]></Title>
                <Description><![CDATA[]]></Description>
                <PicUrl><![CDATA[$pigurl]]></PicUrl>
                <Url><![CDATA[$Link]]></Url>
                </item>";

        $textTpl .= "</Articles></xml>";

        $resultStr = sprintf($textTpl,$fromUsername,$toUsername , $time, $msgType);

        return $resultStr;
    }
    /**
     * 关注
     * @param $object
     * @return string
     */
    public function handleEvent($object)
    {
        $contentStr = "";
        switch ($object->Event)
        {
            case "subscribe":
                //新用户关注事件
                $openid = $object->FromUserName;
                $output = $this->getMpUserInfo($openid);

                try{
                    if(!empty($output->errcode)){
                        throw new Exception("感谢您的关注");
                    }
                    //查找用户是否已使用微信登录
                    if(!empty($output->unionid)){
                        if($PersonalUser = PersonalUser::select('uid','wechatunionid')->where('wechatunionid',$output->unionid)->first()){
                            //使用微信登录过，有unionid,直接绑定用户
                            $PersonalUser->wechatmpopenid = $output->openid;
                            $PersonalUser->save();
                        }
                    }
                    $contentStr ="感谢您的关注,等您好久了!";
                }catch (Exception $e){
                    $contentStr =  'Message: '.$e->getMessage();
                }
                $resultStr = $this->responseText($object, $contentStr);
                break;
            case "CLICK":
                $contentStr = $object->EventKey;
                if(!empty($object->EventKey)){
                    switch($object->EventKey){
                        case "reFresh"://刷新

                            if($user = PersonalUser::select('uid')->where('wechatmpopenid',$object->FromUserName)->first()){

                                if(Resume::where('uid',$user->uid)->update(['updatetime'=>date("Y-m-d H:i:s",time())])){
                                    $contentStr = "简历刷新成功";
                                }else{
                                    $contentStr = "简历刷新失败,<a href='".url("mobile/personal/my_resume")."'>创建一份简历</a>";
                                }

                            }else{

                                //拉取用户信息
                                $openid = $object->FromUserName;
                                $output = $this->getMpUserInfo($openid);
                                //查找用户是否有unionid
                                if(!empty($output->unionid)){
                                    $link = "unionid=".$output->unionid."&openid=$openid";
                                }else{
                                    $link = "openid=$openid";
                                }
                                $contentStr = "/::) "."亲，请先绑定账号，<a href='".url("mobile/personal/binding")."?$link'>绑定账号/注册新账号</a>";

                            }

                            $resultStr = $this->responseText($object, $contentStr);
                            break;
                        case "userMessage"://消息中心

                            if($user = PersonalUser::select('uid','password')->where('wechatmpopenid',$object->FromUserName)->first()){
                                $strPassword = substr($user->password, 0 ,16);//取密码前16
                                $strEncryption = md5($strPassword . date('Y-W'));//拼接当前周数md5加密
                                $redirectType = 1;//验证没通过是否重定向，1是0否
                                $extLink = "str=$strEncryption&redirect=$redirectType";
                                return $this->messageCenter($object, $extLink);
                            }else{
                                //拉取用户信息
                                $openid = $object->FromUserName;
                                $output = $this->getMpUserInfo($openid);
                                //查找用户是否有unionid
                                if(!empty($output->unionid)){
                                    $link = "unionid=".$output->unionid."&openid=$openid";
                                }else{
                                    $link = "openid=$openid";
                                }
                                $contentStr = "/::) "."亲，请先绑定账号，<a href='".url("mobile/personal/binding")."?$link'>绑定账号/注册新账号</a>";
                                $resultStr = $this->responseText($object, $contentStr);
                            }

                            break;
                        case "binDing"://账号绑定

                            //查找用户是否已绑定
                            if($PersonalUser = PersonalUser::select('uid','username')->where('wechatmpopenid',$object->FromUserName)->first()){
                                $contentStr = "/::) 亲爱的".$PersonalUser->username.'，您的账号已绑定完成，如需解绑请点下面链接';
                                $contentStr .= "<a href='".url("personal/clearbinding/".$PersonalUser->uid."/".$object->FromUserName)."'>{解绑账号}</a>";

                            }else{
                                //拉取用户信息
                                $openid = $object->FromUserName;
                                $output = $this->getMpUserInfo($openid);

                                try{
                                    if(!empty($output->errcode)){
                                        throw new Exception("绑定失败");
                                    }
                                    //查找用户是否有unionid
                                    if(!empty($output->unionid)){
                                        $link = "unionid=".$output->unionid."&openid=$openid";
                                    }else{
                                        $link = "unionid=openid=$openid";
                                    }
                                    $contentStr = "/::) "."<a href='".url("mobile/personal/binding")."?$link'>点击->绑定账号/注册新账号</a>";

                                }catch (Exception $e){

                                    $contentStr =  'Message: '.$e->getMessage();
                                    break;

                                }
                            }
                            $resultStr = $this->responseText($object, $contentStr);
                            break;
                        default :

                            break;
                    }
                }

                break;
            default :
                $contentStr = "Unknow Event123: ".$object->Event;
                //$resultStr = $this->responseText($object, $contentStr);//未知事件提示
                $resultStr='';
                break;
        }

        return $resultStr;
    }

    /**
     * 通过openid 拉取公众平台用户信息
     * @param $openid
     * @return mixed
     */
    public function getMpUserInfo($openid){
        //拉取用户信息
        $wechatObj = new \MpWeiXin();
        $ACCESS_TOKEN = $this->tokenValue(0);
        $openid = $openid;  //关注用户onpen id
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$ACCESS_TOKEN&openid=$openid&lang=zh_CN";
        $output = $wechatObj->curlSetopt($url);
        return $output;
    }

    /**
     * 微信解除账号绑定
     * @param $uid
     * @return mixed
     */
    public function clearBinDing($uid,$wechatmpopenid){
        if(!empty($uid)){
            PersonalUser::where('uid',$uid)->update(['wechatopenid'=>NULL,'wechatmpopenid'=>NULL,'wechatunionid'=>NULL]);
            $data = [
                'touser' => $wechatmpopenid,
                'msgtype' => 'text',
                'text' => ['content' => '解绑成功']
            ];
        }else{
            $data = [
                'touser' => $wechatmpopenid,
                'msgtype' => 'text',
                'text' => ['content' => '解绑失败']
            ];
        }

        $access_token = $this->tokenValue(0);
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";

        $data = json_encode($data,JSON_UNESCAPED_UNICODE);//中文不转unicode
        $wechatObj = new \MpWeiXin();
        $wechatObj->pushDate($data,$url);
        $status = "clear";
        return Style::view("mobile/personal/auth/binDingStatus",compact('status'));
    }

    /**
     * 文本消息
     * @param $object
     * @param $content
     * @param int $flag
     * @return string
     */
    public function responseText($object, $content, $flag=0)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }

    /**
     * 获取token,检查时间，提前十分钟更新token
     * @param $catetory
     * @return mixed
     */
    private function tokenValue($catetory){

        $wechatObj = new \MpWeiXin();
        return $wechatObj->checkToken('personal',$catetory);

    }

    /**
     * 微信登录
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function weiXinOpenLogin(Request $request){
        $request->only('code','state');
        $appid =Site::get('mpPersonOpenAppID');
        $secret = Site::get('mpPersonOpenAppSecret');
        $code = $request->code;
        $state = $request->state;
        //获得token
        if($state == Site::get('mpPersonOpenState') && !empty($code)){
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
            $curl = curl_init();
            curl_setopt($curl,CURLOPT_URL,$url);
            curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
            curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
            curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);//以文件流的方式返回
            $output = curl_exec($curl);
            curl_close($curl);
            $get_at_array = json_decode($output);
            //print_r($get_at_array);
            //
            if(is_object($get_at_array)){
                if(empty($get_at_array->access_token) || empty($get_at_array->openid)){
                    return redirect("/personal/login")->with('errMsg','抱歉，微信登录失败，请重新扫一次！！');
                }
                $access_token = $get_at_array->access_token;
                $openid = $get_at_array->openid;
                $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
                $curl = curl_init();
                curl_setopt($curl,CURLOPT_URL,$url);
                curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
                curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
                curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);//以文件流的方式返回
                $output = curl_exec($curl);
                curl_close($curl);
                $getUserInfo = json_decode($output);

                //获得用户信息
                if(empty($getUserInfo->unionid) || empty($getUserInfo->openid)){
                    return redirect("/personal/login")->with('errMsg','抱歉，微信登录失败，请重新扫一次！！');
                }else{
                    $usname = $getUserInfo->nickname;//用户名
                    $userImg = $getUserInfo->headimgurl;//头像

                    $openId = $getUserInfo->openid;
                    $unionid = $getUserInfo->unionid;
                    $PersonalUser = PersonalUser::where('wechatopenid',$openId)->orWhere('wechatunionid',$unionid)->first();

                    $user = auth()->guard('personal')->user();
                    if($PersonalUser){//已注册过
                        Auth::guard('personal')->login($PersonalUser);

                        $user = auth()->guard('personal')->user();
                        //登录记录表
                        $this->loginRecord($user);

                        return redirect("/");
                    }elseif(!empty($user->uid)) {
                        $user->wechatopenid = $openId;
                        $user->wechatunionid = $unionid;
                        $user->save();
                        return redirect("personal/set_account");
                    }else{
                        //查询personLogin 是否等1，等于1直接登录
                        switch(Site::get('mpPersonOpenLogin')){
                            case 0:
                                Session::put('openId', $openId);
                                Session::put('unionid', $unionid);
                                Session::put('userImg', $userImg);
                                Session::put('usname', $usname);
                                return redirect('personal/weixinbinding');
                            break;
                            case 1:
                                if(!empty($openId)){
                                    $rename = $this->rename($usname);
                                    $create =[
                                        'username' => $rename,
                                        'email' => '',
                                        'password' => str_random(60),
                                        'wechatopenid' => $openId,
                                        'wechatunionid' => $unionid?$unionid:null,
                                        'regtime' => date('Y-m-d H:i:s',time()),
                                        'updatetime' => date('Y-m-d H:i:s',time()),
                                        'last_login_time' => date('Y-m-d H:i:s',time()),
                                        'last_login_ip' => getIp()
                                    ];

                                    if($newUser = PersonalUser::create($create)){
                                        Auth::guard('personal')->login($newUser);

                                        $user = auth()->guard('personal')->user();
                                        //登录记录表
                                        $this->loginRecord($user);

                                        return redirect("/");
                                    }else{
                                        return redirect('personal/weixinbinding');
                                    }
                                }
                            break;
                        }
                    }
                }
            }
        }
        return redirect("/personal/login")->with('errMsg','抱歉，微信登录失败，请重新扫一次！！');
    }


    /**
     * 个人微信绑定现在账号
     * @param Request $request
     * @return mixed
     */
    public function WeiXinBinDing(){
        $userImg = session('userImg');
        $usname = session('usname');
        Session::forget('usname');
        $toRegNewUserDir = "personal/newweixinbinding";
        $formDir = "personal/stroyweixinbinding";
        if(Session::has('openId')){
            return Style::view("personal.auth.binDingRegister",compact('userImg','usname','toRegNewUserDir','formDir'));
        }else{
            return redirect('/personal/login');
        }
    }

    /**
     * 个人微信绑定新注册用户
     */
    public function newWeiXinBinDing(){
        if(Session::has('openId')){
            $openId = session('openId');
            $unionid = session('unionid');
            $openIdType = 'mp';
            return Style::view("personal.auth.newBinDingRegister",compact('openId','unionid','openIdType'));//
        }else{
            return redirect('/personal/login');
        }
    }

    /**
     * 保存个人微信绑定openId
     * @param AjaxLoginRequest $request
     * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function stroyWeiXinBinDing(AjaxLoginRequest $request){
        $request->only('username','password');
        $request->flash();
        if(!Session::has('openId')){
            return redirect('/personal/login')->with('errMsg','绑定失败，请重试一下！');
        }
        if(Auth::guard('personal')->attempt(['username' => $request->username, 'password' => $request->password])
            or Auth::guard('personal')->attempt(['mobile' => $request->username, 'password' => $request->password])){
            $user = Auth::guard('personal')->user();

            if(PersonalUser::where('uid',$user->uid)->update(['wechatopenid'=>session('openId'),'wechatunionid'=>session('unionid')])){
                Session::forget('openId');
                Session::forget('unionid');
                Session::forget('userImg');
                Session::forget('usname');
                //登录记录表
                $this->loginRecord($user);

                return redirect('personal/resume_mange');
            }else{
                return back()->withErrors(['handleErr'=>'绑定失败，请重试一下！']);
            }
        }else{
            return back()->withErrors(['handleErr'=>'密码错误！']);
        }
    }

    /**
     * 登录记录信息
     * @param $userInfo
     */
    public function loginRecord($userInfo){
        //登录记录表
        $record = array();
        $record['uid'] = $userInfo->uid;
        $record['personal_login_ip'] = getIp();
        $record['personal_login_time'] = date('Y-m-d H:i:s',time());
        $record['login_type'] = 2;
        $record['type'] = 3;
        //登录记录表
        PersonalLoginRecord::create($record);
        //更新用户表
        $userInfo->last_login_time = date('Y-m-d H:i:s',time());
        $userInfo->last_login_ip = getIp();
        $userInfo->save();
    }
    
    /**
     * 自动登录，重命名用户名
     * @param $usname
     * @return string
     */
    
    protected function rename($usname){
        $PersonalUser = PersonalUser::select('username')->where('username',$usname)->first();
        if($PersonalUser){
            $reusname = $usname.'_'.str_random(8);
            return $this->rename($reusname);
        }else{
            return $usname;
        }
    }
}